/*数据库操作*/
/*http请求*/
const rp = require('request-promise');
const util = require('../../utils/topUtil.js');
//const basics_db = require('../dbhelper/basics_db');
//const apiClient = require('../common/tb_sdk/index.js').ApiClient;

/*根参数*/
const appkey = '25362818';
const appsecret = '38c134ab6dae9fe6223f5e977fce04a3';
const uri = 'http://gw.api.taobao.com/router/rest';

/**
 * 公共请求参数
 */
const publicParams = {
    app_key: appkey,
    sign_method: 'md5',
    timestamp: util.YYYYMMDDHHmmss(),
    format: 'json',
    v: '2.0'
}

/**
 * Sign API request.
 * see http://open.taobao.com/doc/detail.htm?id=111#s6
 *
 * @param  {Object} params
 * @return {String} sign string
 */
function sign(params) {
    var sorted = Object.keys(params).sort();
    var basestring = appsecret;
    for (var i = 0, l = sorted.length; i < l; i++) {
        var k = sorted[i];
        basestring += k + params[k];
    }
    basestring += appsecret;
    return util.md5(basestring).toUpperCase();
};


/**
 * 超级搜索
 * @author jaosnZhang
 * @param {Object} ctx 响应主体文本
 * @param {Function} next 异步函数跳返
 * @return {Object} ctx.body 返回信息对象
 */
exports.superSrearch = async (ctx, next) => {
    /*参数声明*/
    let query = ctx.query;

    /*传参声明*/
    let params = {
        method: 'taobao.tbk.item.get',
        app_key: appkey,
        timestamp: util.YYYYMMDDHHmmss(),
        format: 'json',
        v: '2.0',
        sign_method: 'md5',
        fields: 'num_iid,title,pict_url,reserve_price,zk_final_price,user_type,provcity,item_url,seller_id,volume,nick,tk_comm_fee,tk_common_fee,',
        q: query.q || ''
    }

    /*函数体*/
    let options = {
        uri: uri,
        qs: params,
        headers: {
            'User-Agent': 'Request-Promise'
        },
        json: true // Automatically parses the JSON string in the response
    };

    /*签名*/
    options.qs.sign = sign(params);


    let res;
    await rp(options)
        .then(function (repos) {
            res = repos;
        })
        .catch(function (err) {
            res = err;
        });

    return ctx.body = res;
}

/**
 * 淘宝客商品链接转换
 * @author jaosnZhang
 * @param {Object} ctx 响应主体文本
 * @param {Function} next 异步函数跳返
 * @return {Object} ctx.body 返回信息对象
 */
exports.convert = async (ctx, next) => {
    /*参数声明*/
    let query = ctx.query;

    /*传参声明*/
    let params = Object.assign(publicParams, {
        method: 'taobao.tbk.item.convert',
        fields: 'num_iid,click_url',
        adzone_id: '123',
        platform:'123',
        num_iids: query.num_iids || ''
    }); 

    console.log(params)

    /*函数体*/
    let options = {
        uri: uri,
        qs: params,
        headers: {
            'User-Agent': 'Request-Promise'
        },
        json: true // Automatically parses the JSON string in the response
    };

    /*签名*/
    options.qs.sign = sign(params);


    let res;
    await rp(options)
        .then(function (repos) {
            res = repos;
        })
        .catch(function (err) {
            res = err;
        });

    return ctx.body = res;
}

/**
 * 数据通讯测试
 * @author jaosnZhang
 * @param {Object} ctx 响应主体文本
 * @param {Function} next 异步函数跳返
 * @return {Object} ctx.body 返回信息对象
 */
exports.dataTest = async (ctx, next) => {
    /*数据操作*/
    return ctx.body = { "a": "tongle" };
}
